Page({
  data: {
    book: {},
    chapters: {
      total: 0,
      list: [],
    },
    currentPage: 1, // 当前页码
    pageSize: 50, // 每页显示的章节数
  },

  async onLoad(options) {
    const bookId = options.id;

    // 显示加载圈
    wx.showLoading({
      title: '加载中...',
    });

    try {
      const app = getApp();
      const bookDetail = await app.fetchData(
        `http://1.94.51.11:8849/workdetail/${bookId}`
      );

      bookDetail.updateTime = bookDetail.updateTime.replace('T', ' ');
      const updateDate = bookDetail.updateTime.split(' ')[0];
      bookDetail.update = updateDate; // 设置新的属性 update
      bookDetail.introduce = this.replaceHH(bookDetail.introduce);
      // 设置书籍详情
      this.setData({ book: bookDetail });

      // 加载初始章节数据
      await this.loadChapters(bookId);

      // 在成功获取数据后设置导航栏标题
      wx.setNavigationBarTitle({
        title: this.data.book.name,
      });
    } catch (error) {
      console.error('Failed to fetch book details', error);
    } finally {
      // 隐藏加载圈
      wx.hideLoading();
    }
  },

  async loadChapters(bookId) {
    const { currentPage, pageSize } = this.data;
    await wx.request({
      url: `http://1.94.51.11:8849/workchapter/${bookId}`,
      data: {
        currentPage,
        pageSize,
      },
      success: res => {
        const resData = res.data.data;
        this.setData({
          'chapters.total': resData.total,
          'chapters.list': [...this.data.chapters.list, ...resData.list],
          currentPage: currentPage + 1,
        });
      },
      fail: error => {
        console.error('Failed to fetch chapter details', error);
      },
    });
  },

  onReachBottom() {
    const bookId = this.data.book.id;
    this.loadChapters(bookId);
  },

  goToChapterDetail(event) {
    const chapterId = event.currentTarget.dataset.id;
    const bookId = event.currentTarget.dataset.bookId;
    const totalCount = event.currentTarget.dataset.total;
    wx.navigateTo({
      url: `/pages/chapterDetail/chapterDetail?bookId=${bookId}&chapterId=${chapterId}&total=${totalCount}`,
    });
  },

  replaceHH(str) {
    return str.replace(/<br>/g, '\n');
  },
});
